package hoyo.zqy.pet.service.impl;

import hoyo.zqy.pet.domain.PetType;
import hoyo.zqy.pet.mapper.PetTypeMapper;
import hoyo.zqy.pet.service.IPetTypeService;
import hoyo.zqy.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> petTree() {
        //查询全部数据并封装
        List<PetType> petTypes = petTypeMapper.loadAll();
        //创建一个map接受数据
        Map<Long, PetType> map = new HashMap<>();
        for (PetType petType : petTypes) {
            map.put(petType.getId(),petType);
        }
        //创建一个集合进行接受返回数据
        List<PetType> petTree = new ArrayList<>();
        //循环遍历查询parentId
        for (PetType petType : petTypes) {
            //判断是否具备parentId
            if (petType.getParentId()==null){
                //顶级部门直接保存
                petTree.add(petType);
            }else {
                //不是顶级部门查找父部门
                Long parentId = petType.getParentId();
                //通过id在map中找出父部门
                PetType parentPetType = map.get(parentId);
                //防止数据库脏数据
                if (parentPetType!=null){
                   parentPetType.getChildren().add(petType);
                }
            }
        }
        return petTree;
    }
}
